from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
from django.utils.deconstruct import deconstructible
from mall import settings

@deconstructible
class MyStorage(Storage):
    """
    自定义文件类
    """

    def __init__(self, conf_path=None, ip=None):
        if conf_path is None:
            conf_path = settings.FDFS_CLIENT_CONF
        self.conf_path = conf_path

        if ip is None:
            ip = settings.FDFS_URL
        self.ip = ip

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content, max_length=None):
        # 创建client对象
        client = Fdfs_client(self.conf_path)
        data = content.read()
        result = client.upload_by_buffer(data)
        if result.get('Status') == 'Upload successed.':
            file_id = result.get('Remote file_id')
        else:
            raise Exception('上传失败')
        return file_id

    def exists(self, name):

        # 判断文件是否存在，FastDFS可以自行解决文件的重名问题
        # 所以此处返回False，告诉Django上传的都是新文件
        return False

    # 默认返回name
    def url(self, name):
        # 返回文件的完整URL路径,其实就是remote file_id
        # 我们在访问图片的时候，需要自己加上http://ip:port/
        return self.ip + name
